package com.dk.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.dk.mapper.PersonRoleMapper;
import com.dk.mapper.TPersonMapper;
import com.dk.pojo.LoginTPerson;
import com.dk.pojo.PersonRoleExample;
import com.dk.pojo.TPerson;
import com.dk.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service
@org.springframework.stereotype.Service
public class PersonServiceImpl implements PersonService {
    @Autowired
    private TPersonMapper tPersonMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private PersonRoleMapper personRoleMapper;



    @Override
    public  TPerson selectByTperson(String username) {
        TPerson t = tPersonMapper.selectByPname(username);
        return t;
    }

    //查询所有用户
    @Override
    public List<TPerson> selectTPerson() {
        List<TPerson> tPeople = tPersonMapper.selectByExample(null);
        return tPeople;
    }

    //查询当前用户对象
    @Override
    public TPerson selectById(Integer id) {
        TPerson tPerson = tPersonMapper.selectByPrimaryKey(id);
        return tPerson;
    }

    //查询当前用户的所有角色
    @Override
    public List<Integer> selectByPid(Integer id) {
        List<Integer> list = tPersonMapper.selectByPid(id);
        return list;
    }

    //用户修改
    @Override
    public Boolean updateInto(TPerson tPerson, Integer[] roleId) {
        try {
            //修改用户
            tPersonMapper.updateByPrimaryKeySelective(tPerson);
            //删除中间表
            PersonRoleExample pr = new PersonRoleExample();
            PersonRoleExample.Criteria criteria = pr.createCriteria();
            criteria.andPersonIdEqualTo(tPerson.getPid());
            personRoleMapper.deleteByExample(pr);
            //增加中间表
            personRoleMapper.insertPersonRole(tPerson.getPid(),roleId);
            //同步redis
            redisTemplate.delete("user_tree");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    //删除用户
    @Override
    public Boolean deleteById(Integer id) {
        try {
            //删除用户
            tPersonMapper.deleteByPrimaryKey(id);
            //删除中间表
            PersonRoleExample pr = new PersonRoleExample();
            PersonRoleExample.Criteria criteria = pr.createCriteria();
            criteria.andPersonIdEqualTo(id);
            personRoleMapper.deleteByExample(pr);
            //同步redis
            redisTemplate.delete("user_tree");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    //查询菜单权限
    @Override
    public List<String> selectPermsByUserId(Integer pid) {
        List<String> list = tPersonMapper.selectPermsByUserId(pid);
        return list;
    }
}
